package cn.tlb.compoment.loader;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tlb.xutilsdownload.R;

public class LoaderDemoActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> {
    private static final String TAG = LoaderDemoActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loader_demo);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.button18)
    void init() {
        Bundle bundle = new Bundle();
        bundle.putString("name", "张三");
        getSupportLoaderManager().initLoader(1, bundle, this);
    }

    @OnClick(R.id.button20)
    void init2() {
        Bundle bundle = new Bundle();
        bundle.putString("name", "张三22222");
        getSupportLoaderManager().initLoader(2, bundle, this);
    }

    @OnClick(R.id.button19)
    void reload() {
        getSupportLoaderManager().restartLoader(3, null, this);
    }

    public static class MyAsyncLoader extends AsyncTaskLoader<String> {

        final private String TAG = "MyAsyncLoader";

        public MyAsyncLoader(Context context) {
            super(context);
        }

        @Override
        protected void onStartLoading() {
            super.onStartLoading();
            Log.i(TAG, "onStartLoading");
            forceLoad();
        }

        @Override
        public String loadInBackground() {
            Log.i(TAG, "loadInBackground");
            return "MyAsyncLoader loadInBackground result";
        }

        @Override
        public void deliverResult(String data) {
            Log.i(TAG, "deliverResult data=" + data);

        }

        @Override
        protected void onStopLoading() {
            super.onStopLoading();
            Log.i(TAG, "onStopLoading");
            //cancelLoad();     // Attempt to cancel the current load task if possible

        }

        @Override
        protected void onReset() {
            Log.i(TAG, "onReset");
            super.onReset();
        }
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        Log.i(TAG, String.format("onCreateLoader(%d, %s)", id, args));
        return new MyAsyncLoader(getApplicationContext());
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        Log.i(TAG, String.format("onLoadFinished(data=%s)", data));
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {
        Log.i(TAG, "onLoaderReset");
    }
}
